#import operator
import time
from osv import osv, fields
from osv.orm import intersect
#import tools.sql
#from tools import config
#from tools.translate import _
#from mx import DateTime

#Red Invoice
class kderp_vat_invoice(osv.osv):
    _name="kderp.vat.invoice"
    _description="KDERP VAT Invoice Information"
    
    def _get_currency_from_kpfc(self,cr,uid,context={}):
        res = False
        if 'currency_id' in context:
            res = context['currency_id']
        return res
    
    def _get_new_date(self, cr, uid, context={}):
        res = time.strftime('%Y-%m-%d')
        if context:
            if 'payment_date' in context:
                res = context['payment_date']
        if not res:
            res = time.strftime('%Y-%m-%d')
        return res
    
    def _check_duplicate(self, cr, uid, ids,name, args, context={}):
        res = {}
        for vat in self.browse(cr,uid,ids):
            cr.execute("Select case when count(*)>1 then 'Duplicated' else '' end from kderp_vat_invoice where name='%s'" % vat.name)
            re = cr.fetchone()
            if re:
                res[vat.id] = re[0]
            else:
                res[vat.id] = re[0]=''
        return res
                    
    def _get_new_name(self, cr, uid, context={}):
        res=''
        input_year=False
        #raise osv.except_osv("E",type(date))
        current_year = time.strftime('%Y-%m-%d')
        date = False
        if date:
            input_year = date
        else:
            input_year = current_year
        #raise osv.except_osv("E",input_year)
        cr.execute("""Select
                        prefix || to_char(select_year,suffix) || 
                        lpad((max(substring(current_code from length(prefix || suffix)+1 for padding)::integer)+1)::text,padding,'0') as new_code
                        from
                        (Select
                            case when kvi.name is null then prefix || to_char(select_year,suffix) || lpad('0',padding,'0')  else kvi.name end as current_code,
                            padding,
                            suffix,
                            prefix,select_year
                        from 
                            ir_sequence isq
                        left join
                            (select '%s'::date as select_year) vwtemp_year on 1=1
                        left join
                            kderp_vat_invoice kvi on kvi.name ilike  prefix || to_char(select_year,suffix) || lpad('_',padding,'_')
                        where 
                            code='kderp_vat_invoice' and isq.active) vwcurrent_code
                        group by
                        padding,
                        suffix,
                        prefix,
                        select_year""" % (input_year))
        if cr.rowcount:
            res=cr.fetchone()[0]
    
        return res
    _columns={
             'name':fields.char('Invoice No.',size=25,required=True),
             'date':fields.date('Date',required=True),
             'payment_id':fields.many2one('kdvn.payment.from.client','VAT Invoice'),
             'notes':fields.text('Notes'),
             'check_duplicate':fields.function(_check_duplicate,type='char',size='16',method=True,string='Warning')
             #'type':fields.selection([('in_invoice','Supplier'),('out_invoice','Customer')],'Type',select=True),
             #'job_type': fields.selection([('E','Electrical'),('M','Mechanical'),('ME','M&E')],'Job type', select=True),
             #'customer':fields.many2one('res.partner','Customer'),
             #'currency_id':fields.many2one('res.currency','Currency'),
             #'subtotal':fields.float('Sub-Total'),
             #'tax_percent':fields.float('VAT (%)'),
             #'amount_tax':fields.float('Tax'),
             #'total_amount':fields.float('Total'),
             }
   # _sql_constraints = [('kderp_unique_vat_no','unique(name)','KDERP Error: VAT No. must be unique')]
    _defaults = {
                 'date':_get_new_date,
                 'name':_get_new_name,
                }
    
    def name_get(self, cr, uid, ids, context={}):
        if not len(ids):
            return []
        res = []
        reads = self.read(cr, uid, ids, ['name','date'], context)
        for record in reads:
            name=''
            if record and record['date']:
                name = record['name']+" - "+record['date']
            else:
                name = record['name']
            res.append((record['id'], name))        
        return res

kderp_vat_invoice()